# -*- coding: UTF-8 -*-
import pymysql
from dbutils.pooled_db import PooledDB
from utils.read_yaml import YAML


class MySQLPools:
    """MySQL数据库连接池"""

    def __init__(self):
        self.pool_store = {}
        self.db_information = YAML.ReadRoot("mysql")

    @staticmethod
    def _create_connection(db):
        """获取pymysql连接"""

        def connection_creator():
            return pymysql.connect(
                host=db['HOSTNAME'],
                user=db['USERNAME'],
                passwd=db['PASSWORD'],
                db=db['DATABASE'],
                port=db['PORT'],
                charset=db['DB_CHARSET']
            )

        return connection_creator

    def DynamicCreateConnectionPools(self):
        """动态创建数据库连接池，可以同时创建多个连接池，创建的数量取决于配置文件中配置的数量"""
        try:
            for db in self.db_information:
                self.pool_store[db['DATABASE'] + "_pool"] = PooledDB(
                    creator=MySQLPools._create_connection(db),
                    maxconnections=db['DB_MAX_CONNECTIONS'],
                    mincached=db['DB_MIN_CACHED'],
                    maxcached=db['DB_MAX_CACHED'],
                    blocking=db['DB_BLOCKING'],
                    maxusage=db['DB_MAX_USAGE'],
                    maxshared=db['DB_MAX_SHARED'],
                    setsession=db['DB_SET_SESSION']
                )
            return self.pool_store
        except Exception as e:
            print(f"未知的异常: {e}")

